package com.qmyx.supplychain.quartz.task;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.enums.ExpressEnums;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.PropertiesReader;
import com.kuaidi100.sdk.utils.SignUtils;
import com.ytjj.qmyx.supplychain.common.enums.NeedPhoneExpressEnum;
import com.ytjj.qmyx.supplychain.common.model.response.BankerStoreAddressResponse;
import com.ytjj.qmyx.supplychain.common.utils.DateUtil;
import com.ytjj.qmyx.supplychain.mapper.BankerOrderMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerStoreAddressMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxOrders;
import com.ytjj.qmyx.supplychain.mapper.entity.YxReturnGoods;
import com.ytjj.qmyx.supplychain.service.OrderService;
import com.ytjj.qmyx.supplychain.service.ProductSpecService;
import com.ytjj.qmyx.supplychain.service.ReturnGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class ReturnGoodsTask {

	@Resource
	private ReturnGoodsService returnGoodsService;

	@Resource
	private OrderService orderService;

	@Resource
	private ProductSpecService productSpecService;
	@Resource
	private BankerOrderMapper bankerOrderMapper;
	@Resource
	private BankerStoreAddressMapper bankerStoreAddressMapper;

	/**
	 * 快递更新时间差值 30分钟
	 */
	private static final long DIFFERENCE_VALUE = 1800L;

	/**
	 * 退货物流更新到退款表，
	 * 处理【退货退款】已签收的订单变成待退款
	 */
	@Scheduled(cron = "0 0/30 * * * ?")
	public void verifyReturnGoods() {
		log.info("===== 开始检查退货物流情况 =====");
		AtomicInteger updateTotal = new AtomicInteger();
		try {
			//寄回中的售后单
			List<YxReturnGoods> returnGoodsList = returnGoodsService.selectListByStatus(8);
			//记录已处理的物流
			Map<String, Integer> seen = new HashMap<>();
			returnGoodsList.stream().forEach(item -> {
				String key = item.getReturnExpressCompany() + item.getReturnExpressNo();
				if (null == item.getExpressUpdateTime() || DateUtil.secondBetween(new Date(), item.getExpressUpdateTime()) >= DIFFERENCE_VALUE) {
					Integer value = seen.get(key);
					if (null == value) {
						seen.put(key, 1);
					} else {
						return;
					}
					//过滤默认填充的物流单号
					if ("123456".equals(item.getReturnExpressNo())) {
						return;
					}
					returnGoodsService.dealReturnTrack(item);

					updateTotal.addAndGet(1);
				}
			});
		} catch (Throwable e) {
			log.error("===退货物流情况==={}", e);
		}
		log.info("===== 结束检查退货物流情况,本次更新退货物流总数：{}=====",updateTotal);
	}


	/**
	 * 【补偿任务】修复售后失败的订单的原状态
	 * 每天凌晨2点10分修复订单状态
	 */
	@Scheduled(cron = "0 40 1 * * ?")
	public void repairToOriginalState(){
		log.info("===== 开始修复不正确的售后订单状态 =====");
		returnGoodsService.repairToOriginalStatus();
		log.info("===== 结束修复不正确的售后订单状态 =====");
	}


	/**
	 * 售后类型为【退货退款】,查询已寄回时间已超24小时的供应商未审核的退货数据,
	 * 供应商审核状态改为审核通过,供应商处理时间now,状态变为待退款4
	 */
//	@Scheduled(cron = "0 0/5 * * * ?")
//	public void editBankerStatus() {
//		log.info("===== 开始检查售后类型为退货退款,入库时间超24小时但供应商未审核的退货数据 =====");
//		List<YxReturnGoods> returnGoodsList=returnGoodsService.selectByBankerNotApproved();
//		returnGoodsList.stream().forEach(item -> {
//			returnGoodsService.updateBankerStatusAutoByBankerNotApproved(item.getId());
//		});
//		log.info("===== 结束检查售后类型为退货退款,入库时间超24小时但供应商未审核的退货数据 =====");
//	}


	/**
	 * 查询正在进行售后的的订单状态是否正确,并改正
	 */
//	@Scheduled(cron = "0 0/5 * * * ?")
	public void verifyReturnGoodsOrders(){
		log.info("===== 开始查询正在进行售后的的订单状态是否正确 =====");
		returnGoodsService.verifyReturnGoodsOrders();
		log.info("===== 结束查询正在进行售后的的订单状态是否正确 =====");
	}


	//	@Scheduled(cron = "0 0/30 * * * ?")
	public void verifyBankerRece() {
		log.info("===== 开始检查供应商审核情况 =====");
		returnGoodsService.verifyBankerRece();
		log.info("===== 结束检查供应商审核情况 =====");
	}

	/**
	 * 售后类型为【退款】,查询用户申请售后时间已超24小时的供应商未审核的退货数据,
	 * 供应商审核状态改为审核通过,供应商处理时间now
	 */
//	@Scheduled(cron = "0 0/5 * * * ?")
	public void verifyBankerStatus() {
		List<YxReturnGoods> returnGoodsList=returnGoodsService.selectListByAfterTypeAndBankerStatus();
		returnGoodsList.stream().forEach(item -> {
			returnGoodsService.updateBankerStatusAuto(item.getId());
			//todo 加回库存
			YxOrders yxOrders=orderService.queryByChildOrderNo(item.getChildOrderNo());
			if(null!=yxOrders){
				productSpecService.updateProductSpecStock(yxOrders.getProductSpecId(),yxOrders.getProductSum(),"add");
			}
		});
	}
}
